#include <opencv2/opencv.hpp>
#include <vector>
#include <iostream>
#include "aip-cpp-sdk-0.8.1/face.h"

using namespace cv;
using namespace std;

int main()
{
	string app_id = "19175394";
	string api_key = "rcGnz1NEDIdthZCa1upSYNvG";
	string secret_key = "EML3sUkT6IUCqG6VOECjaHy5697HdkLF";
	aip::Face client(app_id, api_key, secret_key);//创建人脸识别客户端

	VideoCapture cam(0);
	CascadeClassifier classifier("/usr/share/opencv/haarcascades/haarcascade_frontalface_alt2.xml");

	namedWindow("Camera");
	namedWindow("Face"); //显示发送给百度云进行识别的人脸区域

	Mat image;
	Mat gray;

	while(1)
	{
		cam >> image;
		cvtColor(image, gray, COLOR_BGR2GRAY);
		equalizeHist(gray, gray);
		vector<Rect> faces;
		classifier.detectMultiScale(gray, faces);
		if (faces.size())
		{
			rectangle(image, faces[0], CV_RGB(255, 0, 0));
			Mat face(image, faces[0]); //对原图像进行裁剪，仅保留人脸的矩形区域
			imshow("Face", face); //将人脸显示到小窗口
			vector<unsigned char> buf; //保存压缩后的人脸图片
			imencode(".jpg", face, buf); //将人脸图片压缩为jpeg格式
            //将jpeg格式的人脸图片编码为BASE64字符串
			string faceimg = aip::base64_encode((char*)buf.data(), buf.size());
            //将人脸图片发送给百度云进行识别，识别结果保存到json对象中
			Json::Value json = client.search(faceimg, "BASE64", "group1", aip::null);
			Json::StyledWriter writer;
            //将识别结果转换为json字符串，显示在标准输出上
			cout << writer.write(json) << endl;
		}
		imshow("Camera", image);
		if (waitKey(40) != 255)
		{
			break;
		}
	}
}
